package com.cqhfan.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.cqhfan.common.constants.BizConstants;
import com.cqhfan.common.exceptions.UnLoginException;
import com.cqhfan.common.utils.JwtUtil;
import com.cqhfan.common.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author 眭传洪
 * @create 2024-11-14
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    private final String publicKey;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate, String publicKey) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.publicKey = publicKey;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拿到token
        String token = request.getHeader(BizConstants.LOGIN_AUTH_HEADER);
        if (StrUtil.isBlank(token)) {
            throw new UnLoginException();
        }

        // 解析token
        Claims claims = JwtUtil.parseToken(token, publicKey);
        if (claims == null) {
            throw new UnLoginException();
        }
        Long userId = claims.get(BizConstants.TOKEN_USER_INFO, Long.class);

        // 存到threadLocal
        UserContext.setUser(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserContext.removeUser();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
